import axios from 'axios';
import {useUserStore} from '@/stores/index.js'
import router from '@/router/index.js';

const baseURL = '/api';

const instance = axios.create({
    //基地址和超时时间
    baseURL,
    timeout: 10000,
})

//请求拦截器
instance.interceptors.request.use(
    (config) => {
        //携带token
        const userStore = useUserStore();
        if (userStore.token) {
            config.headers.Authorization = userStore.token;
        }
        return config;
    },
    (error) => Promise.reject(error)
);

//响应拦截器
instance.interceptors.response.use(
    (response) => {
        //code为0 是处理成功
        if (response.data.code === 0) {
            return response;
        }

        //处理失败
        ElMessage.error(response.data.message || "服务异常");
        return Promise.reject(response.data);
    },
    (error) => {
        //如果是401 是权限不足或者token过期，拦截到登录界面
        if (error.response?.status === 401) {
            router.push('/login');
        }

        ElMessage.error(error.response.data.message || "服务异常");
        return Promise.reject(error);
    }
)

export default instance;
export {baseURL};


//响应格式, {"code":0 , "message": "", "data":{}}
